import { forwardRef, memo, useEffect, useRef, useState } from 'react';
import { Box, Checkbox, Input, Select, Switch } from '@alifd/next';
import st from './index.module.scss';
import { useRequest } from 'ice';
import PropertyService from '@/pages/CommodityCenter/PropertyManage/service';
import { SelectRequestConfig } from '@/pages/CommodityCenter/CommodityManage/entity';

interface StandardValue {
  checked: boolean;
  propertyId?: number;
  propertyValues?: string;
}

interface Props {
  value?: StandardValue;
  defaultValue?: StandardValue;
  onChange?: (value: StandardValue) => void;
  isPreview?: boolean;
}

const StandardItem = ({ value, onChange, isPreview, defaultValue }: Props, ref) => {
  const { checked, propertyId, propertyValues } = value || defaultValue || {} as any;
  const [currentProperty, setCurrentProperty] = useState<PropertyState.PropertyItem>({} as any);

  const { data: propertyList, request: propertyRequest } = useRequest(PropertyService.getPropertyPage, {
    ...SelectRequestConfig,
    manual: true,
  });

  useEffect(() => {
    setCurrentProperty({} as any);
    if (!isPreview && checked && !propertyList.length) {
      propertyRequest({ current: 1, pageSize: 10 }, { enable: true });
    }
  }, [isPreview, checked]);

  const changeSwitch = (_c: boolean) => {
    onChange &&
      onChange({
        checked: _c,
        propertyId: undefined,
        propertyValues: '',
      });
  };

  const changeProperty = (p: number) => {
    const current = propertyList.find((item) => item.id === p);
    setCurrentProperty(current || {});
    onChange &&
      onChange({
        checked,
        propertyId: p,
        propertyValues: '',
      });
  };

  const changePropertyValue = (val: string | string[]) => {
    onChange &&
      onChange({
        checked,
        propertyId,
        propertyValues: Array.isArray(val) ? val.join(',') : val,
      });
  };

  const searchProperty = (val: string) => {
    propertyRequest({ current: 1, pageSize: 10 }, { name: val, enable: true });
  };

  return (
    <div className={st.Standard} ref={ref}>
      {isPreview && !checked ? (<span>无</span>) : (
        <Switch
          autoWidth
          size="small"
          checkedChildren="开"
          unCheckedChildren="关"
          checked={checked}
          onChange={changeSwitch}
          style={{ display: isPreview ? 'none' : 'inline-block' }}
        />
      )}
      <div className={st.property} style={{ display: checked ? 'block' : 'none' }}>
        {isPreview ? (
          <div>{`规格：${propertyValues}`}</div>
        ) : (
          <Box spacing={10} direction="row">
            <Select
              showSearch
              filterLocal={false}
              onSearch={searchProperty}
              dataSource={propertyList}
              value={propertyId}
              onChange={changeProperty}
              placeholder="搜索属性名称"
            />
            {currentProperty.modeType === 1 ? (
              <Select
                dataSource={currentProperty.attrValues?.split(',').map((it) => ({ value: it, label: it }))}
                placeholder="请选择"
                value={propertyValues}
                style={{ width: '100%' }}
                onChange={changePropertyValue}
              />
            ) : null}
            {currentProperty.modeType === 2 ? (
              <Input
                placeholder="请输入属性描述"
                value={propertyValues}
                onChange={changePropertyValue}
              />
            ) : null}
            {currentProperty.modeType === 3 ? (
              <Checkbox.Group
                dataSource={currentProperty.attrValues?.split(',').map((it) => ({ value: it, label: it }))}
                placeholder="请选择"
                value={propertyValues?.split(',').filter((it) => !!it) || []}
                onChange={changePropertyValue}
              />
            ) : null}
          </Box>
        )}
      </div>
    </div>
  );
};

export default memo(forwardRef(StandardItem));
